<template>
  <section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="query">
				<el-form-item>
					<el-input v-model="query.keyword" placeholder="关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="search">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

    <!--列表-->
    <el-table :data="pageInfo.rows" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="id" label="Id" width="120">
      </el-table-column>
      <el-table-column prop="name" label="名字" width="120">
      </el-table-column>
      <el-table-column prop="sn" label="SN" width="350">
      </el-table-column>
      <el-table-column label="操作" width="350">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
          <el-button type="primary" size="small" @click="handlePermission(scope.$index, scope.row)">设置权限</el-button>
          <el-button type="success" size="small" @click="handleMenu(scope.$index, scope.row)">设置菜单</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="query.currentPage"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="query.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageInfo.total" style="float:right;">
      </el-pagination>
    </el-col>


		<!--新增界面-->
		<el-dialog title="新增" :visible.sync="addFormVisible" :close-on-click-modal="false">
			<el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm">
				<el-form-item label="姓名" prop="name">
					<el-input v-model="addForm.name" auto-complete="off"></el-input>
				</el-form-item>
        <el-form-item label="SN"  prop="name">
          <el-input v-model="addForm.sn" auto-complete="off"></el-input>
        </el-form-item>
        
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="addFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
			</div>
		</el-dialog>



    <el-dialog title="设置权限" :visible.sync="setPermissionVisible" :close-on-click-modal="false">
      <el-form :model="rolePermission" label-width="80px" ref="saveForm">
        <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
        <div class="checkbox-table" v-for="(p,indexkey) in permissionTree" :key="p.sn">
          <template>
            <el-checkbox class="check1" style="font-weight: 600;margin-bottom: 15px "
                         v-model='rolePermission.permissionSns' :label="p.sn"
                         @change='handleCheck(1,indexkey)'>
              {{p.name}}
            </el-checkbox>
            <div style="margin-bottom: 20px;">
              <div v-for="c in p.children" class="line-check" :key="c.sn"
                   style="display: inline-block; margin-left: 20px;margin-bottom: 20px;" >
                <el-checkbox class="check2" @change='handleCheck(2,indexkey)'
                             v-model="rolePermission.permissionSns" :label="c.sn">
                  {{c.name}}
                </el-checkbox>
              </div>
            </div>
          </template>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="setPermissionVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveRolePermission" :loading="addLoading">提交</el-button>
      </div>
    </el-dialog>


    <el-dialog title="设置菜单" :visible.sync="setMenuVisible" :close-on-click-modal="false">
      <el-form :model="rolemenu" label-width="80px" ref="saveForm">
        <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChangeMenu">全选</el-checkbox>
        <div class="checkbox-table" v-for="(p,indexkey) in menuTree" :key="p.id">
          <template>
            <el-checkbox class="check1" style="font-weight: 600;margin-bottom: 15px "
                         v-model='rolemenu.menuid' :label="p.id"
                         @change='handleCheckMenu(1,indexkey)'>
              {{p.name}}
            </el-checkbox>
            <div style="margin-bottom: 20px;">
              <div v-for="c in p.children" class="line-check" :key="c.id"
                   style="display: inline-block; margin-left: 20px;margin-bottom: 20px;" >
                <el-checkbox class="check2" @change='handleCheckMenu(2,indexkey)'
                             v-model="rolemenu.menuid" :label="c.id">
                  {{c.name}}
                </el-checkbox>
              </div>
            </div>
          </template>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="setMenuVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveMenu" :loading="addLoading">提交</el-button>
      </div>
    </el-dialog>
    </section>
</template>


<script>
	import util from '../../common/js/util'
	//import NProgress from 'nprogress'
	import { getUserListPage, removeUser, batchRemoveUser, editUser, addUser } from '../../api/api';

	export default {
		data() {
			return {

				filters: {
					name: ''
				},
        pageInfo:{
          total:0,
          rows:[]
        },
        query:{
          currentPage:1,
          pageSize:10,
          keyword:""
        },
				listLoading: false,
				sels: [],//列表选中列

        setPermissionVisible:false,

        setMenuVisible:false,
				addFormVisible: false,//新增界面是否显示
				addLoading: false,
				addFormRules: {
					name: [
						{ required: true, message: '请输入信息', trigger: 'blur' }
					]
				},
				//新增界面数据
				addForm: {
          id:null,
          name:"",
          sn:"",
        },
        rolePermission:{
          roleId:null,
          permissionSns:[],  // 存放的是当前被勾选中的权限,包括一级权限和二级权限
        },
        permissionTree:[],
        isIndeterminate:false,    // 用来控制全选框的状态
        checkAll:false,  // 控制全选框是否勾选中
        allPermissionSns:[],

        rolemenu:{
          roleId:null,
          menuid:[],  // 存放的是当前被勾选中的权限,包括一级权限和二级权限
        },
        allmenus:[],
        menuTree:[],



      }

		},
		methods: {

      saveRolePermission(){
        this.$http.post("/role/permission",this.rolePermission)
            .then(result => {
              result = result.data;
              if(result.success){
                this.$message({message: '设置成功!', type: 'success'});
                // 关闭弹框
                this.setPermissionVisible = false;
              }else{
                this.$message({message: result.message, type: 'error'});
              }
            })
      },
      saveMenu(){
        this.$http.post("/role/menu",this.rolemenu)
            .then(result => {
              result = result.data;
              if(result.success){
                this.$message({message: '设置成功!', type: 'success'});
                // 关闭弹框
                this.setMenuVisible = false;
              }else{
                this.$message({message: result.message, type: 'error'});
              }
            })

      },

      handleMenu(index,row){
        this.setMenuVisible=true;
        this.getMenuTree();
        this.getAllmenuid();
        this.rolemenu.roleId = row.id;
        this.getmenubyid(row.id)

      },
      getmenubyid(roleID){
        this.$http.get("/menu/getrolemenu/"+roleID)
            .then(res =>{
              res =res.data;
              if(res.success){
                console.log(res)
                this.rolemenu.menuid = res.data;
              }
            })
      },
      getAllmenuid(){
        this.$http.get("/role/ids")
            .then(result => {
              result = result.data;
              if(result.success){
                console.log(result.data)
                // result.resultObj 后端返回的所有的权限sn
                this.allmenus = result.data;
              }
            })
      },

      getMenuTree(){
        this.$http.get("/role/menutree")
            .then(result => {
              result = result.data;
              if(result.success){
                // 查询成功,将后端返回的数据赋值给this.permissionTree
                this.menuTree = result.data;
                console.log(result.data)
              }
            })
      },



      handleCheckAllChangeMenu(val){
        debugger;
        this.rolemenu.menuid = val ? this.allmenus : [];
        this.isIndeterminate = false;
      },
      // 处理选择事件  type 1:一级权限2:二级权限   a：一级权限的索引位置
      handleCheckMenu(type, a = 0) { // 多选框
        debugger
        // 在已选中的权限列表中，查看是否存在一级权限 >-1 存在  <0 不存在
        let indexOf = this.rolemenu.menuid.indexOf(this.menuTree[a].id);
        if (type == 2) { // 二级菜单点击
          let index = 0;  //
          this.menuTree[a].children.map(item => {
            // 已选中的权限列表中，是否包含当前一级权限下的某个子权限
            if (this.rolemenu.menuid.indexOf(item.id) > -1) {
              index += 1;
            }
          })
          if (index > 0) {  // 已选中的权限列表中，包含当前一级权限下的某个子权限
            if (indexOf < 0) {  // 已选中的权限列表中，没有当前一级权限，则添加到已选中的权限列表中
              this.rolemenu.menuid.push(this.menuTree[a].id);
            }
          } else {  // // 已选中的权限列表中，不包含当前一级权限下的某个子权限
            if (indexOf > -1) {// 已选中的权限列表中，有当前一级权限，则删除
              this.rolemenu.menuid.splice(indexOf, 1);
            }
          }
        } else {  // 一级菜单点击
          if (indexOf > -1) { // 已选中的权限中，包含当前一级权限，则将该一级权限下所有的子权限选中
            this.menuTree[a].children.map(item => {
              if (this.rolemenu.menuid.findIndex((n) => n == item.id) < 0) {
                this.rolemenu.menuid.push(item.id)
              }
            })
          } else {
            // 已选中的权限中，不包含当前一级权限，则将该一级权限下所有的子权限移除
            this.menuTree[a].children.map(item => {
              if (this.rolemenu.menuid.findIndex((n) => n == item.id) > -1) {
                this.rolemenu.menuid.splice(this.rolemenu.menuid.findIndex((n) => n == item.id), 1);
              }
            })
          }
        }
        debugger;
        // 获取已选中的长度
        let checkedCount = this.rolemenu.menuid.length;
        debugger
        // 如果已选中的长度==所有权限的长度，则checkAll=true，也就是全选框被选中
        this.checkAll = checkedCount === this.allmenus.length;
        // 如果已选中的长度>0并且已选中的长度<所有权限的长度，则全选框是一个横杠
        debugger
        this.isIndeterminate = checkedCount > 0 && checkedCount < this.allmenus.length;
      },



      handlePermission(index,row){
        this.setPermissionVisible = true;
        this.getPermissionTree();
        this.getAllPermissionSn();
        this.rolePermission.roleId = row.id;
        this.getSnsbyid(row.id)
      },

      getSnsbyid(roleID){
         this.$http.get("/permission/"+roleID)
             .then(res =>{
                res =res.data;
                if(res.success){
                    this.rolePermission.permissionSns = res.data;
                }
             })
      },


      getPermissionTree(){
        this.$http.get("/permission/tree")
            .then(result => {
              result = result.data;
              if(result.success){
                // 查询成功,将后端返回的数据赋值给this.permissionTree
                this.permissionTree = result.data;
              }
            })
      },
      getAllPermissionSn(){
        this.$http.get("/permission/permissionSns/sns")
            .then(result => {
              result = result.data;
              if(result.success){
                console.log(result.data)
                // result.resultObj 后端返回的所有的权限sn
                this.allPermissionSns = result.data;
              }
            })
      },


      handleCheckAllChange(val){
        this.rolePermission.permissionSns = val ? this.allPermissionSns : [];
        this.isIndeterminate = false;
      },
      // 处理选择事件  type 1:一级权限2:二级权限   a：一级权限的索引位置
      handleCheck(type, a = 0) { // 多选框
        // 在已选中的权限列表中，查看是否存在一级权限 >-1 存在  <0 不存在
        let indexOf = this.rolePermission.permissionSns.indexOf(this.permissionTree[a].sn);
        if (type == 2) { // 二级菜单点击
          let index = 0;  //
          this.permissionTree[a].children.map(item => {
            // 已选中的权限列表中，是否包含当前一级权限下的某个子权限
            if (this.rolePermission.permissionSns.indexOf(item.sn) > -1) {
              index += 1;
            }
          })
          if (index > 0) {  // 已选中的权限列表中，包含当前一级权限下的某个子权限
            if (indexOf < 0) {  // 已选中的权限列表中，没有当前一级权限，则添加到已选中的权限列表中
              this.rolePermission.permissionSns.push(this.permissionTree[a].sn);
            }
          } else {  // // 已选中的权限列表中，不包含当前一级权限下的某个子权限
            if (indexOf > -1) {// 已选中的权限列表中，有当前一级权限，则删除
              this.rolePermission.permissionSns.splice(indexOf, 1);
            }
          }
        } else {  // 一级菜单点击
          if (indexOf > -1) { // 已选中的权限中，包含当前一级权限，则将该一级权限下所有的子权限选中
            this.permissionTree[a].children.map(item => {
              if (this.rolePermission.permissionSns.findIndex((n) => n == item.sn) < 0) {
                this.rolePermission.permissionSns.push(item.sn)
              }
            })
          } else {
            // 已选中的权限中，不包含当前一级权限，则将该一级权限下所有的子权限移除
            this.permissionTree[a].children.map(item => {
              if (this.rolePermission.permissionSns.findIndex((n) => n == item.sn) > -1) {
                this.rolePermission.permissionSns.splice(this.rolePermission.permissionSns.findIndex((n) => n == item.sn), 1);
              }
            })
          }
        }
        // 获取已选中的长度
        let checkedCount = this.rolePermission.permissionSns.length;
        // 如果已选中的长度==所有权限的长度，则checkAll=true，也就是全选框被选中
        this.checkAll = checkedCount === this.allPermissionSns.length;
        // 如果已选中的长度>0并且已选中的长度<所有权限的长度，则全选框是一个横杠
        this.isIndeterminate = checkedCount > 0 && checkedCount < this.allPermissionSns.length;
      },
      

		  search(){
        this.query.currentPage = 1;
        this.getRoles()
      },

      handleCurrentChange(val) {
        this.query.currentPage = val;
        this.getRoles()
      },

      handleSizeChange(val){
        this.query.pageSize=val;
        this.getRoles()
      },

      getRoles(){
        this.$http.post("/role",this.query)
            .then(result => {
              result = result.data;
              this.pageInfo = result.data;
            }).catch(result => {
          this.$message({ message: '员工分页查询失败',type: 'error'});
        })
      },

			//删除  index:当前数据的行号    row:当前行数据
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?','提示',{
					type: 'warning'
				}).then(() => {
					this.listLoading = true;  //加载框 true-加载

          let id=row.id;
          this.$http.delete("/role/"+id).then(res =>{
            this.listLoading=false;
            res=res.data;
            if(res.success){
              this.$message({message: '删除成功', type: 'success'});
            }else {
              this.$message({message:res.message, type: 'error'});
            }
            this.query.currentPage=1
            this.getRoles()
          })

				}).catch(() => {
              this.$message('删除操作已取消')
				});
			},
			//显示编辑界面
      handleEdit: function (index,row) {
        this.addFormVisible = true;
        //将当前对象赋值给addform  回显
        this.addForm=Object.assign({},row);
        if(!row.dept){
          this.addForm.dept={
            id:null,
            name:""
          };

        }



      },
			//显示新增界面
			handleAdd: function () {
				this.addFormVisible = true;
				this.addForm = {
          id:null,
          username: "",
          password:"",
          email:"",
          headImage:"",
          age:"",
          dept:{
            id:null,
            name:""
          },
				};
			},
			//新增
			addSubmit: function () {
				this.$refs.addForm.validate((valid) => {
					if (valid) {
              this.$confirm('确定提交？','提示',{}).then(() =>{
                 this.addLoading=true;
                 let para = Object.assign({},this.addForm);


                  this.$http.put("/role",para).then(res =>{
                     res=res.data;
                     this.addLoading=false;
                     if(res.success){
                       this.$message({message: '保存成功', type: 'success'});
                       this.query.currentPage=1;
                       this.getRoles();
                       this.addFormVisible=false;
                     }else {
                       this.$message({message: res.message, type: 'error'});
                     }
                  }).catch(res =>{
                    this.$message({message: '网络错误', type: 'error'});
                  })
              })
					}
				});
			},
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
				var ids = this.sels.map(item => item.id)
        console.log(ids)
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					this.$http.patch("/role",ids).then(res =>{
					  res= res.data;
					  if(res.success){
              this.$message({message: '删除成功', type: 'success'});
              this.listLoading=false;
              this.query.currentPage=1;
              this.getRoles()
					  }else {
              this.$message({message: res.message, type: 'error'});
            }
          })


				}).catch(() => {
          this.$message({message: '取消删除', type: 'error'});
				});
			}
		},


		mounted() {
      this.getRoles()
		}
	}

</script>

<style scoped>

</style>